package org.theconservationagency;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import org.theconservationagency.utils.YearExtractor;

public class SortPublicationsByYears {
	
	public static void main(String[] args) throws IOException, FileNotFoundException {
		
		if (args.length<4) {
			System.err.println("Usage: xxx.jar org.theconservationagency.SortPublicationsByYears [INPUT] [OUTPUT] [EARLIEST_YEAR] [LATEST_YEAR]");
			System.exit(1);
		}
		
		String input = args[0];
		String output = args[1];
		int earliest = Integer.parseInt(args[2]);
		int latest = Integer.parseInt(args[3]);
		
		TreeMap<Integer, TreeSet<String>> map = new TreeMap<Integer, TreeSet<String>>();
		
		BufferedReader br = new BufferedReader(new FileReader(input));
		
		try {
			
			String line = null;
			int year;
			YearExtractor extractor = new YearExtractor(earliest, latest);
			
			int rowsProcessed = 0;
			
			while ((line=br.readLine())!=null) {
				
				year = extractor.extractYear(line);
				
				TreeSet<String> set = map.get(year);
				
				if (set==null) {
					set = new TreeSet<String>();
				}
				
				set.add(line.trim());
				map.put(year, set);
				
				rowsProcessed++;
				if (rowsProcessed%500==0) {
					System.err.println("" + rowsProcessed + " rows are processed.");
				}
			}
			
			System.err.println("" + rowsProcessed + " rows are processed in total.");
			
		} finally {
			br.close();
		}
		
		BufferedWriter bw = new BufferedWriter(new FileWriter(output));
		
		try {
			
			Integer key = map.lastKey();
			int rowsProcessed = 0;			
			
			while(key!=null) {
				
				System.err.println("Processing year=" + key + " ..." );
				
				rowsProcessed += writeSet(bw, map.get(key));
				map.remove(key);
				key = map.lowerKey(key);
				
			}
			
			System.err.println("" + rowsProcessed + " are written in total.");
			
		} finally {
			bw.close();
		}
		
		System.err.println("Finish!");
		
	}
	
	private static int writeSet(BufferedWriter bw, Set<String> set) throws IOException {
		Iterator<String> it = set.iterator();
		int rowsProcessed = 0;
		while(it.hasNext()) {
			rowsProcessed++;
			bw.write(it.next());
			bw.write("\r\n\r\n");
		}
		return rowsProcessed;
	}
}
